import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20*1000,
})
//后端返回值类型
export interface ServiceResponse<T>{
  code: number
  msg: string
  data:T
}
export const request =<T>(url: string, method: Method = 'GET', submitData?: object) => {
  //返回Promise
  //request(默认data类型,后端返回值类型)
  return service.request<T,ServiceResponse<T>>({
    url: url,
    method: method,
    // []插值表达式 得到 对象的键名称
    //请求参数:GET请求用params,否则用data
    [method.toUpperCase()==='GET'?'params':'data']: submitData
  })
}
service.interceptors.request.use(
  config => {
    const { token } = useUserStore()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    // 响应拦截器中，减少了一层 data
    return response.data
  },
  error => {
    if (error.response) {
      //提示错误信息
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('网络错误，请稍后再试')
    }
    if (error.response.status === 401) {
      //跳转到登录页
      router.push('/login')
      const store = useUserStore()
      store.cleanToken()
    }
    return Promise.reject(error)
  },
)

export default service
